import QRCode from 'qrcode'

/**
 * 生成二维码数据URL
 * @param data 要编码的数据
 * @param options 二维码选项
 * @returns Promise<string> 二维码的dataURL
 */
export const generateQRCodeDataURL = async (
  data: string,
  options: {
    width?: number
    height?: number
    margin?: number
    color?: {
      dark?: string
      light?: string
    }
  } = {}
): Promise<string> => {
  try {
    const defaultOptions = {
      width: options.width || 200,
      height: options.height || 200,
      margin: options.margin || 2,
      color: {
        dark: options.color?.dark || '#000000',
        light: options.color?.light || '#FFFFFF'
      },
      errorCorrectionLevel: 'M' as const
    }

    const dataURL = await QRCode.toDataURL(data, defaultOptions)
    return dataURL
  } catch (error) {
    console.error('生成二维码失败:', error)
    throw error
  }
}

/**
 * 生成二维码Canvas
 * @param data 要编码的数据
 * @param canvas Canvas元素
 * @param options 二维码选项
 */
export const generateQRCodeCanvas = async (
  data: string,
  canvas: HTMLCanvasElement,
  options: {
    width?: number
    height?: number
    margin?: number
    color?: {
      dark?: string
      light?: string
    }
  } = {}
): Promise<void> => {
  try {
    const defaultOptions = {
      width: options.width || 200,
      height: options.height || 200,
      margin: options.margin || 2,
      color: {
        dark: options.color?.dark || '#000000',
        light: options.color?.light || '#FFFFFF'
      },
      errorCorrectionLevel: 'M' as const
    }

    await QRCode.toCanvas(canvas, data, defaultOptions)
  } catch (error) {
    console.error('生成二维码Canvas失败:', error)
    throw error
  }
}

/**
 * 生成微信登录二维码数据
 * @param timestamp 时间戳
 * @returns 微信登录二维码数据
 */
export const generateWeChatQRData = (timestamp: number = Date.now()): string => {
  const randomId = Math.random().toString(36).substr(2, 9)
  return `wechat_login_${timestamp}_${randomId}`
}

/**
 * 生成QQ登录二维码数据
 * @param timestamp 时间戳
 * @returns QQ登录二维码数据
 */
export const generateQQQRData = (timestamp: number = Date.now()): string => {
  const randomId = Math.random().toString(36).substr(2, 9)
  return `qq_login_${timestamp}_${randomId}`
}

/**
 * 检查是否为移动端
 * @returns boolean
 */
export const isMobile = (): boolean => {
  // #ifdef H5
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
  // #endif
  
  // #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-QQ || APP-PLUS
  return true
  // #endif
  
  return false
}
